require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIArenaTicketPurchase = {};
HelperFunc.SetUIEnv(UIArenaTicketPurchase)
local this = UIArenaTicketPurchase;

this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;

this.btnBgClose = nil;
this.txtItemName = nil;
this.imgItemIcon = nil;
this.imgCostIcon = nil;
this.txtCostCount = nil;
this.btnBuy = nil;
this.txtRemainCount = nil;
this.txtCount = nil;

this.arenaBaseInfo = nil;

this.itemConfig = nil;

function UIArenaTicketPurchase.Init( _arena_type )--todo 应该小写 暂时先大写 _arena_type竞技场类型
    this.cur_arena_type = _arena_type and tonumber(_arena_type) or EnumConst.ArenaBattleType.Normal
    if this.itemConfig == nil then
        this.itemConfig = G.dataTable["t_item"]
    end

    local name, packageName = getUIName(PanelResNames.UIArenaTicketPurchase);
    panelMgr:Push(name, packageName, this.onCreate,Config.useLocalUI);
end

function UIArenaTicketPurchase.onCreate(obj)

    if not hasInit then
        hasInit = true;
        btnBgClose = obj:GetChild("BgClose");
        txtItemName = obj:GetChild("ItemName");
        imgItemIcon = obj:GetChild("ItemIcon");
        imgCostIcon = obj:GetChild("CostIcon");
        txtCostCount = obj:GetChild("CostCount");
        txtCount = obj:GetChild("Count");
        btnBuy = obj:GetChild("BuyButton");
        txtRemainCount = obj:GetChild("RemainCount");
        
        this.addEvent();
    end

    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        this.refresh(logicMgr.ArenaManager.getBaseInfo())
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        this.refresh(logicMgr.ArenaManager.getCrossBaseInfo())
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        this.refresh(logicMgr.ArenaManager.getCrossTeamBaseInfo()) 
    else
        error("错误竞技场类型")
    end
end

function UIArenaTicketPurchase.addEvent()
    btnBgClose.onClick:Add(this.onClickBack)
    btnBuy.onClick:Add(this.onClickBuy)
end

function UIArenaTicketPurchase.removeEvent()
    btnBgClose.onClick:Remove(this.onClickBack)
    btnBuy.onClick:Remove(this.onClickBuy)
end

function UIArenaTicketPurchase.LocalListenEvent()
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        ListenEvent(Config.EventType.Fresh_ArenaTicket,this.receiveTicket)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        ListenEvent(Config.EventType.Fresh_CrossArenaTicket,this.receiveTicket)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        ListenEvent(Config.EventType.Fresh_CrossTeamArenaTicket,this.receiveTicket)
    else
        --todo
    end
end

function UIArenaTicketPurchase.LocalCloseEvent()
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then 
        CloseEvent(Config.EventType.Fresh_ArenaTicket, this.receiveTicket)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        CloseEvent(Config.EventType.Fresh_CrossArenaTicket, this.receiveTicket)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        CloseEvent(Config.EventType.Fresh_CrossTeamArenaTicket, this.receiveTicket)
    else
        error("错误竞技场类型")
    end
end

function UIArenaTicketPurchase.OnDestroy()
    this.removeEvent()
    this.itemConfig = nil
end

function UIArenaTicketPurchase.OnEnable()
    this.LocalListenEvent()
end

function UIArenaTicketPurchase.OnDisable()
    this.LocalCloseEvent()
end

function UIArenaTicketPurchase.GetCostItem( tb_cost, cur_count )
    if tb_cost ~= nil then
        local num = #tb_cost
        local ret = nil
        for k=1, num do
            if cur_count < tb_cost[k][1] then
                return tb_cost[k];
                --if tb_cost[k-1] ~= nil then
                --    ret =  tb_cost[k-1]
                --end
            end
        end
        return ret
    end
    return nil
end

function UIArenaTicketPurchase.refresh(baseInfo) --刷新函数
    arenaBaseInfo = baseInfo
    local arenaTicketData = nil
    local itemCg = nil
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then 
        arenaTicketData =decodeJsonStrToTabel(G.dataTable["t_global"]["73"].f_string_value)
         itemCg = itemConfig[tostring(CurrencyEnum.ChallengeTicket)]
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then  
        arenaTicketData =decodeJsonStrToTabel(G.dataTable["t_global"]["378"].f_string_value)
        itemCg = itemConfig[tostring(CurrencyEnum.CrossChallengeTicket)]
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then 
        local tb_cost_item = decodeJsonStrToTabel(G.dataTable["t_global"]["417"].f_string_value)
        -- local max_count =decodeJsonStrToTabel(G.dataTable["t_global"]["418"].f_int_value)
        itemCg = itemConfig[tostring(CurrencyEnum.CrossTeamChallengeTicket)]
        arenaTicketData = {}
        arenaTicketData[1] = 10
        local cost_item = this.GetCostItem( tb_cost_item, arenaBaseInfo.buyCount )
        arenaTicketData[2] = cost_item and cost_item[3] or 0
    else
        --todo
        error("错误竞技场类型")
        return
    end

    local buyCountMax = arenaTicketData[1]
    local buyCostNum = arenaTicketData[2]
    txtItemName.text = getLanguage(itemCg.f_ItemName)
    imgItemIcon.url = EnumConst.AtlasPath.ItemAtlas..itemCg.f_Icon
    local costCg = itemConfig[tostring(CurrencyEnum.GOLD)]
    imgCostIcon.url = EnumConst.AtlasPath.ItemAtlas..costCg.f_Icon
 
    txtCostCount.text = tostring(buyCostNum)
    txtCount.text = getNumString(logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD))
    txtRemainCount.text = tostring(buyCountMax - arenaBaseInfo.buyCount)
    if buyCountMax - arenaBaseInfo.buyCount <= 0 then
        btnBuy.grayed = true
        btnBuy:GetChild("title").text = getLanguage("ErrorCode_3454")
    else
        btnBuy.grayed = false
        btnBuy:GetChild("title").text = "购买"
    end
end


function UIArenaTicketPurchase.onClickBack()
    closeUI(PanelNames.UIArenaTicketPurchase)
end


function UIArenaTicketPurchase.onClickBuy()
    local arenaTicketData = nil
    local flag = true
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then 
        arenaTicketData = decodeJsonStrToTabel(G.dataTable["t_global"]["73"].f_string_value) 
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then  
        arenaTicketData =decodeJsonStrToTabel(G.dataTable["t_global"]["378"].f_string_value) 
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then 
        local tb_cost_item = decodeJsonStrToTabel(G.dataTable["t_global"]["417"].f_string_value) 
        local max_count =decodeJsonStrToTabel(G.dataTable["t_global"]["418"].f_int_value) 
        local own_num = logicMgr.ItemManager.getBagNumByTableID(CurrencyEnum.CrossTeamChallengeTicket)
        flag = false
        if own_num >= max_count then
            UISysTips.AddMsg(getLanguage("ErrorCode_3419"))
            closeUI(PanelNames.UIArenaTicketPurchase)
            return
        end
        local cost_item = this.GetCostItem( tb_cost_item, arenaBaseInfo.buyCount )
        -- arenaTicketData = {}
        -- arenaTicketData[1] = max_count
        -- arenaTicketData[2] = cost_item and cost_item[3] or 0
        if cost_item == nil then -- arenaBaseInfo.buyCount >= tonumber(cost_item and cost_item[1] or 0)  then
            UISysTips.AddMsg("今日购买次数已满")
            closeUI(PanelNames.UIArenaTicketPurchase)
            return
        end
    else 
        error("错误竞技场类型")
        return
    end

    if flag then
        local buyCountMax = arenaTicketData[1]
        local buyCostNum = arenaTicketData[2] 
        if arenaBaseInfo.buyCount >= buyCountMax  then
            UISysTips.AddMsg("今日购买次数已满")
            closeUI(PanelNames.UIArenaTicketPurchase)
            return
        end 
        if buyCostNum > logicMgr.ItemManager.getBagNumByTableID(CurrencyEnum.GOLD) then
            UISysTips.AddMsg("货币不足无法购买")
            AudioManager.Play(2010)
            closeUI(PanelNames.UIArenaTicketPurchase)
            return
        end
    end
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        arenaHandler.sendBuyTicket(1)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        crossArenaHandler.sendCrossBuyTicket(1)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then 
        crossTeamArenaHandler.sendReqHighArenaBuyTicket( 1 )
    else
        error("错误竞技场类型")
    end 
 
end

function UIArenaTicketPurchase.receiveTicket()
    UISysTips.AddMsg("购买成功");
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        this.refresh(logicMgr.ArenaManager.getBaseInfo())
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        this.refresh(logicMgr.ArenaManager.getCrossBaseInfo())
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        this.refresh(logicMgr.ArenaManager.getCrossTeamBaseInfo())
    else
        error("错误竞技场类型")
    end 
    closeUI(PanelNames.UIArenaTicketPurchase)
end


return UIArenaTicketPurchase
